#!/usr/bin/env python

import time
import unittest
import os

from dropio.client import *

TEST_IMAGE_JPG = "test_image.jpg"
TEST_IMAGE_PNG = "test_image.png"
TEST_MOVIE_FLV = "test_movie.flv"
TEST_AUDIO_MP3 = "test_audio.mp3"
TEST_AUDIO_WAV = "test_audio.wav"
TEST_FILE_IMAGE_GIF_URL = "http://www.ikea.com/ms/img/header/logo.gif"

# used for create file, copy file, move file, also for creating, emptying, deleting multiple drops
PROCESS_WAIT_TIME = 1

CREATE_DROP_PARAM_DICT = {
    "description":"test_description",
    "email_key":"test_email_key",
    "max_size":"42"
    }

GET_DROP_RESPONSE_BODY_PARAMS_LIST = [
    "name",
    "email",
    "max_bytes",
    "current_bytes",
    "asset_count",
    "expires_at",
    "description",
    ]


class DropIoClientBaseTestCase(unittest.TestCase):
    
    def setUp(self):
        # todo ugly hack start
        # http://stackoverflow.com/questions/1842168/python-unit-test-pass-command-line-arguments-to-setup-of-unittest-testcase
        # pass parameters to test case via module globals
        for (k, v) in test_params_dict.items():
            setattr(self, k, v)
        # todo ugly hack end
        
        # attempt to delete self.available_drop_name
        for c in [self.client, self.client2]:
            for dn in [self.available_drop_name, self.available_drop_name2]:
                try: c.delete_drop(self.dn)
                except: pass
        
        self.drops_at_start = []
        for c in [self.client, self.client2]:
            if c is not None:
                self.drops_at_start += [(c, [d.name for d in c.get_drops()])]
    
    # tearDown is not run if setUp fails, risk of removing other than newly created
    # drops is thereby minimized
    def tearDown(self):
        for (c, old_drops) in self.drops_at_start:
            for drop in c.get_drops():
                if not drop.name in old_drops:
                    c.delete_drop(drop)


class _DropIoTextTestResult(unittest._TextTestResult):
    def __init__(self, stream, descriptions, verbosity):
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
        self.verbosity = verbosity

    def startTest(self, test):
        unittest._TextTestResult.startTest(self, test)
        if self.verbosity > 2:
            self.test_start_time = time.time()

    def stopTest(self, test):
        unittest._TextTestResult.stopTest(self, test)
        if self.verbosity > 2:
            self.stream.writeln("Ran test in %.3fs" % (time.time() - self.test_start_time))


class DropIoTextTestRunner(unittest.TextTestRunner):
    def _makeResult(self):
        return _DropIoTextTestResult(self.stream, self.descriptions, self.verbosity)

